package com.vviton.zyhj.admin.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vviton.zyhj.admin.service.ZyddglService;
import com.vviton.zyhj.common.base.AppConfig;
import com.vviton.zyhj.common.base.BaseService;
import com.vviton.zyhj.common.common.CodeConstants;
import com.vviton.zyhj.common.common.ExcelConstants;
import com.vviton.zyhj.common.common.GlobalConstants;
import com.vviton.zyhj.common.common.ValidatorConstants;
import com.vviton.zyhj.common.dao.TYyxtDdglDhjlbMapper;
import com.vviton.zyhj.common.dao.TYyxtJyglDhwlxxMapper;
import com.vviton.zyhj.common.dao.TYyxtPtglCyfxxMapper;
import com.vviton.zyhj.common.entity.TYyxtCode;
import com.vviton.zyhj.common.entity.TYyxtDdglDhjlb;
import com.vviton.zyhj.common.entity.TYyxtJyglDhwlxx;
import com.vviton.zyhj.common.entity.TYyxtPtglCyfxx;
import com.vviton.zyhj.common.utils.DateUtils;
import com.vviton.zyhj.common.utils.ErrorBean;
import com.vviton.zyhj.common.utils.ExcelUtil;
import com.vviton.zyhj.common.utils.ExpressQueryUtils;
import com.vviton.zyhj.common.utils.ResultJson;
import com.vviton.zyhj.common.utils.page.Page;
import com.vviton.zyhj.common.view.ParamDdcx;
import com.vviton.zyhj.common.view.ParamDdfh;
import com.vviton.zyhj.common.view.ViewDdcx;
import com.vviton.zyhj.common.view.ViewDhwlxx;
import com.vviton.zyhj.common.view.ViewKdxx;
import com.vviton.zyhj.common.view.ViewWlgzxx;

/**
 * ClassName: ZyddglServiceImpl <br/>
 * Function: 自营订单管理ServiceImpl. <br/>
 * Date: 2016年11月15日 下午1:34:07 <br/>
 *
 * @author Dengshiyu
 * @version 1.0
 * @since JDK 1.7
 */
public class ZyddglServiceImpl extends BaseService implements ZyddglService {

    /** 日志 */
    private static Logger logger = Logger.getLogger(ZyddglServiceImpl.class);

    /** 读取配置文件信息 */
    @Autowired
    private AppConfig appConfig;

    /** 兑换记录表Mapper */
    @Autowired
    private TYyxtDdglDhjlbMapper tYyxtDdglDhjlbMapper;

    /** 兑换物流信息Mapper */
    @Autowired
    private TYyxtJyglDhwlxxMapper tYyxtJyglDhwlxxMapper;

    /** 承运方信息Mapper */
    @Autowired
    private TYyxtPtglCyfxxMapper tYyxtPtglCyfxxMapper;

    /**
     * getDdcxPagination,根据各种条件查询订单. <br/>
     * Author: Dengshiyu <br/>
     * Create Date: 2016年11月15日 <br/>
     * ===============================================================<br/>
     * Modifier: Dengshiyu <br/>
     * Modify Date: 2016年11月15日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param paramDdcx 订单查询参数
     * @param zh 帐号
     * @return Page
     * @since JDK 1.7
     */
    @Override
    public Page getDdcxPagination(ParamDdcx paramDdcx, String zh) {
        Page page = new Page();
        if (StringUtils.isBlank(paramDdcx.getYwy())) {
            logger.info("订单查询业务域不能为空！");
            return page;
        }
        paramDdcx.setTgflx(CodeConstants.TGFLX_PT);
        paramDdcx.setHzfid(appConfig.getAdminKtId());

        page.setParam(paramDdcx);
        Integer total = tYyxtDdglDhjlbMapper.getDdcxTotalPagination(page);
        page.setTotal(total);
        // 分页查询数据
        page.setPageSize(paramDdcx.getPageSize());
        page.setCurrPage(paramDdcx.getCurrPage());
        if (total > 0) {
            List<ViewDdcx> viewDdcxList = tYyxtDdglDhjlbMapper.getDdcxPagination(page);
            // 字段解析
            Map<String, TYyxtCode> dhlbMap = this.getCodeMapCodeclass(CodeConstants.DHLB);
            Map<String, TYyxtCode> dhztMap = this.getCodeMapCodeclass(CodeConstants.DHZT);
            TYyxtCode tYyxtCode = null;
            for (ViewDdcx viewDdcx : viewDdcxList) {
                tYyxtCode = dhlbMap.get(CodeConstants.DHLB + viewDdcx.getDdlb());
                if (tYyxtCode != null) {
                    viewDdcx.setDdlbDesc(tYyxtCode.getCodedesc());
                }
                tYyxtCode = dhztMap.get(CodeConstants.DHZT + viewDdcx.getZt());
                if (tYyxtCode != null) {
                    viewDdcx.setZtDesc(tYyxtCode.getCodedesc());
                }
            }
            page.setData(viewDdcxList);
        }
        return page;
    }

    /**
     * ddfh,订单发货. <br/>
     * Author: Dengshiyu <br/>
     * Create Date: 2016年11月18日 <br/>
     * ===============================================================<br/>
     * Modifier: Dengshiyu <br/>
     * Modify Date: 2016年11月18日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param paramDdfh 订单发货参数
     * @param zh 帐号
     * @return 操作结果
     * @since JDK 1.7
     */
    @Override
    public ResultJson ddfh(ParamDdfh paramDdfh, String zh) {
        ResultJson result = new ResultJson(false);
        if (StringUtils.isBlank(paramDdfh.getYwy())) {
            result.setMessage(ValidatorConstants.E1501);
            return result;
        }
        if (StringUtils.isBlank(paramDdfh.getDhid())) {
            result.setMessage(ValidatorConstants.E1502);
            return result;
        }
        List<ErrorBean> errCodeList = new ArrayList<ErrorBean>();
        ErrorBean errorBean = null;
        if (StringUtils.isBlank(paramDdfh.getShfs())) {
            errorBean = new ErrorBean();
            errorBean.setErrorData(ValidatorConstants.E1503);
            errCodeList.add(errorBean);
        }
        if (paramDdfh.getShfs().equals(CodeConstants.SHFS_KD)) {
            if (StringUtils.isBlank(paramDdfh.getCyfbh()) && StringUtils.isBlank(paramDdfh.getCyfmc())) {
                errorBean = new ErrorBean();
                errorBean.setErrorData(ValidatorConstants.E1504);
                errCodeList.add(errorBean);
            }
            if (StringUtils.isBlank(paramDdfh.getHydh())) {
                errorBean = new ErrorBean();
                errorBean.setErrorData(ValidatorConstants.E1505);
                errCodeList.add(errorBean);
            }
            if (errCodeList.size() > 0) {
                result.setErrorList(errCodeList);
                return result;
            }
        }
        TYyxtJyglDhwlxx tYyxtJyglDhwlxx = new TYyxtJyglDhwlxx();
        tYyxtJyglDhwlxx.setDhid(paramDdfh.getDhid());
        tYyxtJyglDhwlxx.setShfs(paramDdfh.getShfs());
        tYyxtJyglDhwlxx.setCyfbh(paramDdfh.getCyfbh());
        if (StringUtils.isNotBlank(paramDdfh.getCyfbh())) {
            TYyxtPtglCyfxx tYyxtPtglCyfxx = tYyxtPtglCyfxxMapper.getCyfxxById(paramDdfh.getCyfbh());
            if (tYyxtPtglCyfxx != null) {
                tYyxtJyglDhwlxx.setCyfmc(tYyxtPtglCyfxx.getCyfmc());
                tYyxtJyglDhwlxx.setCyfbm(tYyxtPtglCyfxx.getCyfbm());
            }
        } else {
            tYyxtJyglDhwlxx.setCyfmc(paramDdfh.getCyfmc());
        }
        tYyxtJyglDhwlxx.setHydh(paramDdfh.getHydh());
        tYyxtJyglDhwlxx.setYwy(paramDdfh.getYwy());
        tYyxtJyglDhwlxx.setVersions(this.getVersion());
        tYyxtJyglDhwlxx.setDelflag(GlobalConstants.DELFLAG_UPDATE);
        tYyxtJyglDhwlxx.setOperatercode(zh);
        tYyxtJyglDhwlxx.setOperatetime(new Date());
        int count = tYyxtJyglDhwlxxMapper.updateCyfxxByDhid(tYyxtJyglDhwlxx);
        if (count > 0) {
            TYyxtDdglDhjlb tYyxtDdglDhjlb = new TYyxtDdglDhjlb();
            tYyxtDdglDhjlb.setId(paramDdfh.getDhid());
            tYyxtDdglDhjlb.setZt(CodeConstants.DHZT_YFF);
            tYyxtDdglDhjlb.setYwy(paramDdfh.getYwy());
            tYyxtDdglDhjlb.setVersions(this.getVersion());
            tYyxtDdglDhjlb.setDelflag(GlobalConstants.DELFLAG_UPDATE);
            tYyxtDdglDhjlb.setOperatercode(zh);
            tYyxtDdglDhjlb.setOperatetime(new Date());
            count = tYyxtDdglDhjlbMapper.updateDdzt(tYyxtDdglDhjlb);
            if (count > 0) {
                result.setResult(true);
            }
        }
        return result;
    }

    /**
     * getDdxxById,根据Id获取订单信息. <br/>
     * Author: Dengshiyu <br/>
     * Create Date: 2016年11月21日 <br/>
     * ===============================================================<br/>
     * Modifier: Dengshiyu <br/>
     * Modify Date: 2016年11月21日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param id 订单id
     * @param ywy 业务域
     * @return 订单查询结果
     * @since JDK 1.7
     */
    @Override
    public ViewDdcx getDdxxById(String id, String ywy) {
        ViewDdcx viewDdcx = null;
        if (StringUtils.isNotBlank(id)) {
            viewDdcx = tYyxtDdglDhjlbMapper.getDdxxById(id, ywy);
        }
        return viewDdcx;
    }

    /**
     * pldcDdxx,批量导出订单信息. <br/>
     * Author: Dengshiyu <br/>
     * Create Date: 2016年11月24日 <br/>
     * ===============================================================<br/>
     * Modifier: Dengshiyu <br/>
     * Modify Date: 2016年11月24日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param ddids 订单id
     * @param ywy 业务域
     * @param res HttpServletResponse
     * @return 操作结果
     * @since JDK 1.7
     */
    @Override
    public ResultJson pldcDdxx(String ddids, String ywy, HttpServletResponse res) {
        ResultJson result = new ResultJson(false);
        if (StringUtils.isBlank(ywy)) {
            result.setMessage(ValidatorConstants.E1501);
            return result;
        }
        if (StringUtils.isBlank(ddids)) {
            result.setMessage(ValidatorConstants.E1502);
            return result;
        }
        String[] ddidArr = ddids.split(",");
        List<ViewDdcx> viewDdcxList = tYyxtDdglDhjlbMapper.getDdcxListByIds(ddidArr, ywy);
        // 字段解析
        Map<String, TYyxtCode> dhlbMap = this.getCodeMapCodeclass(CodeConstants.DHLB);
        Map<String, TYyxtCode> dhztMap = this.getCodeMapCodeclass(CodeConstants.DHZT);
        TYyxtCode tYyxtCode = null;
        for (ViewDdcx viewDdcx : viewDdcxList) {
            tYyxtCode = dhlbMap.get(CodeConstants.DHLB + viewDdcx.getDdlb());
            if (tYyxtCode != null) {
                viewDdcx.setDdlbDesc(tYyxtCode.getCodedesc());
            }
            tYyxtCode = dhztMap.get(CodeConstants.DHZT + viewDdcx.getZt());
            if (tYyxtCode != null) {
                viewDdcx.setZtDesc(tYyxtCode.getCodedesc());
            }
            viewDdcx.setDhsjFormat(DateUtils.format(viewDdcx.getDhsj(), DateUtils.PATTERN_DATETIME));
        }
        if (CollectionUtils.isNotEmpty(viewDdcxList)) {
            if (StringUtils.isNotBlank(appConfig.getLang())) {
                ExcelUtil.exportTemplate(res, ExcelConstants.ZYDDGL_TEMPLATE_PATH, viewDdcxList, ExcelConstants.ZYDDGL_FILENAME_EN);
            } else {
                ExcelUtil.exportTemplate(res, ExcelConstants.ZYDDGL_TEMPLATE_PATH, viewDdcxList, ExcelConstants.ZYDDGL_FILENAME);
            }

            result.setResult(true);
        }
        return result;
    }

    /**
     * getDhwlxx,根据订单Id获取订单物流信息. <br/>
     * Author: Dengshiyu <br/>
     * Create Date: 2016年12月23日 <br/>
     * ===============================================================<br/>
     * Modifier: Dengshiyu <br/>
     * Modify Date: 2016年12月23日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param ddid 订单id
     * @return 订单物流信息
     * @since JDK 1.7
     */
    @Override
    public ViewDhwlxx getDdwlxx(String ddid) {
        ViewDhwlxx dhwlxx = tYyxtJyglDhwlxxMapper.getViewDhwlxxByDhid(ddid);
        return dhwlxx;
    }

    /**
     * getWlgzxx,根据订单Id查询物流跟踪信息. <br/>
     * Author: Dengshiyu <br/>
     * Create Date: 2016年12月23日 <br/>
     * ===============================================================<br/>
     * Modifier: Dengshiyu <br/>
     * Modify Date: 2016年12月23日 <br/>
     * Modify Description: <br/>
     * ===============================================================<br/>
     *
     * @param ddid 订单编号
     * @return 物流跟踪信息
     * @since JDK 1.7
     */
    @Override
    public ViewWlgzxx getWlgzxx(String dhid) {

        TYyxtJyglDhwlxx dhwlxx = tYyxtJyglDhwlxxMapper.getDhwlxxByDhid(dhid);
        ViewWlgzxx wlgz = new ViewWlgzxx();
        if (dhwlxx != null && StringUtils.isNotBlank(dhwlxx.getCyfbm()) && StringUtils.isNotBlank(dhwlxx.getHydh())) {
            //调用物流信息的接口
            try {
                JSONObject wlgzxx = ExpressQueryUtils.getExpressInfo(dhwlxx.getCyfbm(), dhwlxx.getHydh());

                String flag = wlgzxx.getString("flag");
                wlgz.setExpSpellName(wlgzxx.getString("expSpellName"));
                wlgz.setExpTextName(wlgzxx.getString("expTextName"));
                wlgz.setMailNo(wlgzxx.getString("mailNo"));
                wlgz.setTel(wlgzxx.getString("tel"));
                wlgz.setUpdate(wlgzxx.getString("update"));
                wlgz.setStatus(wlgzxx.getString("status"));
                wlgz.setUpdateStr(wlgzxx.getString("updateStr"));
                wlgz.setRet_code(wlgzxx.getString("ret_code"));
                if ("true".equals(flag)) {
                    wlgz.setFlag(true);
                    List<ViewKdxx> viewKdxxList = new ArrayList<ViewKdxx>();
                    JSONArray wlgzxxArray = wlgzxx.getJSONArray("data");
                    if (wlgzxxArray != null) {
                        Iterator<Object> iterator = wlgzxxArray.iterator();
                        while (iterator.hasNext()) {
                            JSONObject expTemp = (JSONObject) iterator.next();
                            ViewKdxx kdxx = new ViewKdxx();
                            kdxx.setContext(expTemp.getString("context"));
                            kdxx.setTime(expTemp.getString("time"));
                            viewKdxxList.add(kdxx);
                        }
                        wlgz.setKdxxList(viewKdxxList);
                    }

                } else {
                    wlgz.setFlag(false);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            wlgz.setFlag(false);
        }
        return wlgz;
    }

}
